package com.small.nacos.naming.misc;


import com.alibaba.nacos.common.http.AbstractApacheHttpClientFactory;
import com.alibaba.nacos.common.http.HttpClientBeanHolder;
import com.alibaba.nacos.common.http.HttpClientConfig;
import com.alibaba.nacos.common.http.HttpClientFactory;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @Author zhoujin
 * @Date 2022/11/1 9:34
 */
public class HttpClientManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientManager.class);

    private static final NacosRestTemplate APACHE_NACOS_REST_TEMPLATE;

    private static final HttpClientFactory APACHE_SYNC_HTTP_CLIENT_FACTORY = new ApacheSyncHttpClientFactory();

    static {
        // build nacos rest template
        APACHE_NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(APACHE_SYNC_HTTP_CLIENT_FACTORY);
    }

    public static NacosRestTemplate getApacheRestTemplate() {
        return APACHE_NACOS_REST_TEMPLATE;
    }

    private static class ApacheSyncHttpClientFactory extends AbstractApacheHttpClientFactory {

        @Override
        protected HttpClientConfig buildHttpClientConfig() {
            return HttpClientConfig.builder().setConnectionTimeToLive(500, TimeUnit.MILLISECONDS)
                    .setMaxConnTotal(Runtime.getRuntime().availableProcessors() * 2)
                    .setMaxConnPerRoute(Runtime.getRuntime().availableProcessors()).setMaxRedirects(0).build();
        }

        @Override
        protected Logger assignLogger() {
            return LOGGER;
        }
    }
}
